using System;

namespace Be.Timvw.Framework.Security
{
    public class TimeOneTimePassword : HmacOneTimePassword
    {
        public const int DefaultTimeStepSeconds = 30;
        public static readonly DateTime DefaultEpoch = DateTimeHelper.UnixEpoch;

        private readonly DateTime epoch;
        private readonly int timeStep;

        public TimeOneTimePassword(string secret)
        : this(DefaultAlgorithmName, secret, DefaultNumberOfDigits, DefaultEpoch, DefaultTimeStepSeconds)
        {
        }

        public TimeOneTimePassword(string hmacAlgorithmName, string secret, int numberOfDigits, DateTime epoch, int timeStep)
        : base(hmacAlgorithmName, secret, numberOfDigits)
        {
            this.epoch = epoch;
            this.timeStep = timeStep;
        }

        public virtual string GetPassword()
        {
            return this.GetPassword(DateTime.UtcNow);
        }

        public virtual string GetPassword(DateTime iterationTime)
        {
            return base.GetPassword(this.GetIterationNumber(iterationTime));
        }

        public virtual long GetIterationNumber(DateTime iterationTime)
        {
            return (long) ((iterationTime - this.epoch).TotalSeconds / this.timeStep);
        }
    }
}